第三方套件 lodash
// 使用 lodash 的 cloneDeep 方法進行深拷貝
const obj2 = _.cloneDeep(obj1);
obj2.name = "jacky";
obj2.info.age = 100;
console.log("使用 lodash 的 cloneDeep 方法:");
console.log("原始物件:", obj1);
console.log("深拷貝後的物件:", obj2);
JSON.parse()
// 使用 JSON.parse(JSON.stringify(obj)) 方法進行深拷貝
const deepCopy = (obj) => {
return JSON.parse(JSON.stringify(obj));
};
const obj3 = deepCopy(obj1);
obj1.info.interest.code = "C#";
console.log("使用 JSON.parse(JSON.stringify(obj)) 方法:");
console.log("原始物件:", obj1);
console.log("深拷貝後的物件:", obj3);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Day25 lodash深拷貝</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script>
const obj1 = {
name: "12345",
info: {
age: 12,
address: "taiwan",
sex: "boy",
interest: {
code: "javascript",
sports: "basketball",
watch: "movie",
},
},
};
// 使用 lodash 的 cloneDeep 方法進行深拷貝
const obj2 = _.cloneDeep(obj1);
obj2.name = "jacky";
obj2.info.age = 100;
console.log("使用 lodash 的 cloneDeep 方法:");
console.log("原始物件:", obj1);
console.log("深拷貝後的物件:", obj2);
// 使用 JSON.parse(JSON.stringify(obj)) 方法進行深拷貝
const deepCopy = (obj) => {
return JSON.parse(JSON.stringify(obj));
};
const obj3 = deepCopy(obj1);
obj1.info.interest.code = "C#";
console.log("使用 JSON.parse(JSON.stringify(obj)) 方法:");
console.log("原始物件:", obj1);
console.log("深拷貝後的物件:", obj3);
</script>
</body>
</html>